package com.truthbean.jeetb.utils.web;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import static com.truthbean.jeetb.utils.web.invoker.Invoker.PAGE_CHARSET;

public class UploadBean {
    private String fileName = null;
    private String suffix = null;
    private String savePath = "";
    private ServletInputStream sis = null;
    private byte[] b = new byte[1024];

    public UploadBean() {
    }

    public void setSavePath(String path) {
        this.savePath = path;
    }

    public void parseRequest(HttpServletRequest request) throws IOException {
        sis = request.getInputStream();
        int a = 0;
        int k = 0;
        String s = "";
        while ((a = sis.readLine(b, 0, b.length)) != -1) {
            s = new String(b, 0, a, PAGE_CHARSET);
            if ((k = s.indexOf("filename=\"")) != -1) {
                s = s.substring(k + 10);
                k = s.indexOf("\"");
                s = s.substring(0, k);
                File tF = new File(s);
                if (tF.isAbsolute()) {
                    fileName = tF.getName();
                } else {
                    fileName = s;
                }
                k = s.lastIndexOf(".");
                suffix = s.substring(k + 1);
                upload();
            }
        }
    }

    private void upload() {
        try {
            FileOutputStream out = new FileOutputStream(new File(savePath, fileName));
            int a = 0;
            int k = 0;
            String s = "";
            while ((a = sis.readLine(b, 0, b.length)) != -1) {
                s = new String(b, 0, a);
                if ((k = s.indexOf("Content-Type:")) != -1) {
                    break;
                }
            }
            sis.readLine(b, 0, b.length);
            while ((a = sis.readLine(b, 0, b.length)) != -1) {
                s = new String(b, 0, a);
                if ((b[0] == 45) && (b[1] == 45) && (b[2] == 45) && (b[3] == 45) && (b[4] == 45)) {
                    break;
                }
                out.write(b, 0, a);
            }
            out.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}